import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';

import '../../../../lib_runtime/logger.dart';
import '../../interface/room_page_model.dart';

mixin RoomLifecycleMixin<T extends StatefulWidget> on State<T>
    implements WidgetsBindingObserver {
  late RoomPageModel model;

  @override
  void initState() {
    super.initState();
    model = context.read<RoomPageModel>();
    model.roomModel.hideOverlay();
    model.initGiftAnimationController(
        this as SingleTickerProviderStateMixin<StatefulWidget>, context);

    WidgetsBinding.instance.addObserver(this);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      model.mounted = true;
    });
    updateBrightKeepOn();

    RLog.i('RoomPage:initState');
  }

  updateBrightKeepOn() async {
    Future.delayed(const Duration(seconds: 3)).then((value) {
      // if (mounted) FlutterCommon().setScreenBrightKeepOn();
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    RLog.i('RoomPage:didChangeDependencies');
  }

  @override
  void didUpdateWidget(covariant T oldWidget) {
    super.didUpdateWidget(oldWidget);
    RLog.i('RoomPage:didUpdateWidget');
  }

  @override
  void dispose() {
    // model.joinUserList.clear();
    if (model.userJoinAnimationController?.isAnimating ?? false) {
      model.userJoinAnimationController?.dispose();
    }
    model.userJoinAnimationController = null;
    WidgetsBinding.instance.removeObserver(this);

    // 息屏
    // FlutterCommon().setScreenBrightKeepOff();
    RLog.i('RoomPage:dispose');

    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    RLog.i("RoomPage:didChangeAppLifecycleState");
    model.cycleState = state;
    if (state == AppLifecycleState.resumed) {
      RLog.i("切换到了前台");
    } else if (state == AppLifecycleState.paused) {
      // model.joinUserList.clear();
      RLog.i("切换到了后台");
    }
  }
}
